import {
  Typography,
  Paper,
  IconButton,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Button,
} from '@mui/material';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import { useUserStore } from '../store/userStore';
import { useState } from 'react';
import { User } from '../types/User';
import UserForm from '../components/UserForm';

export default function AdminUsers() {
  const { users, deleteUser } = useUserStore();
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [showForm, setShowForm] = useState(false);

  const handleEdit = (user: User) => {
    setEditingUser(user);
    setShowForm(true);
  };

  return (
    <div>
      <Typography variant="h4" gutterBottom>
        Admin User Management
      </Typography>
      <Button
        variant="contained"
        color="success"
        onClick={() => {
          setEditingUser(null);
          setShowForm(true);
        }}
        sx={{ mb: 2 }}
      >
        + Add Admin
      </Button>

      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>Name</TableCell>
              <TableCell>Email</TableCell>
              <TableCell>Role</TableCell>
              <TableCell>Actions</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {users
              .filter((user) => user.role === 'Admin')
              .map((user) => (
                <TableRow key={user.id}>
                  <TableCell>{user.name}</TableCell>
                  <TableCell>{user.email}</TableCell>
                  <TableCell>{user.role}</TableCell>
                  <TableCell>
                    <IconButton onClick={() => handleEdit(user)}>
                      <EditIcon />
                    </IconButton>
                    <IconButton onClick={() => deleteUser(user.id)} color="error">
                      <DeleteIcon />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
          </TableBody>
        </Table>
      </TableContainer>

      {showForm && (
        <UserForm user={editingUser!} onClose={() => setShowForm(false)} />
      )}
    </div>
  );
}
